<?php
namespace app\app\controller;

use think\Controller;
class Login extends Controller {
    // app登录，用户密码验证
    public function verify() {
        if(request()->isPost()) {
            //获取相关的数据
            $data = input('post.');
            $type = $data['type'];
            // 识别是否有验证码
            if($type == 'enableCode') {
                $loginImgCode = $data['code'];
            } else if($type == 'disableCode'){
                $loginImgCode = false;
            }
            $curDate = $data['curdate'];
            $sign = $data['sign'];
            $username = $data['username'];
            $password = $data['password'];
            // 通过用户名 获取 用户相关信息
            $ret = model('AppUser')->get(['username'=>$username]);
            if($ret){
                $sqlPwd = $ret->password;
                $code = $ret->code;
                // 生成签名
                $verifySign = strtoupper(md5(strtolower(md5($data['username'] . $password . sha1($curDate))) . $code));
                $postSign = strtoupper(md5($sign . $code));
                // 比较签名、密码、验证码
                if($verifySign === $postSign && $sqlPwd === md5($password . 'changyuannet')) {
                    if($loginImgCode) {
                        // 验证码检测
                        $captcha = new \think\captcha\Captcha();
                        if (!$captcha->check($loginImgCode)) {
                            // 验证码不正确
                            $code = 4004;
                        } 
                    }
                    // 验证通过
                     $appUserData = [
                         'expire_time' => time() + 300,
                         'access_token' => $postSign,
                     ];
                     $addAccessToken = model('AppUser')->updateById($appUserData, $ret->id);
                     if($addAccessToken) {
                         $code = 4000;
                         // 同时删除 model('AppLoginError')表中对应用户的数据
                         model('AppLoginError')->deleteByUsername($username);
                     } else {
                         // 保存access_token失败
                         $code = 4003;
                     }
                } else {
                    // 密码不正确
                    $code = 4002;
                } 
            } else {
                // 用户名不存在
                $code = 4001;
            }
            return json_encode($code);
        }
    }

    public function md5() {
        var_dump(md5(md5('123456') . 'changyuannet'));
                    
    }
    

}